import numpy as np
from scipy.spatial.distance import cdist
import time

# 生成高维向量数据
def generate_high_dim_vectors(num_points=1000, dimensions=50):
    """生成随机高维向量"""
    np.random.seed(42)
    data = np.random.rand(num_points, dimensions)
    return data

# 生成 50 维随机向量数据
high_dim_vectors = generate_high_dim_vectors(num_points=1000, dimensions=50)

# 计算空间覆盖率
def calculate_coverage(data, threshold):
    """计算空间覆盖率"""
    pairwise_distances = cdist(data, data, metric='euclidean')
    coverage = np.mean(pairwise_distances < threshold)
    return coverage

# 设置阈值为平均最近邻距离的 1.5 倍
pairwise_distances = cdist(high_dim_vectors, high_dim_vectors, metric='euclidean')
np.fill_diagonal(pairwise_distances, np.inf)  # 忽略自身距离
mean_nearest_distance = np.mean(np.min(pairwise_distances, axis=1))
threshold = mean_nearest_distance * 1.5

coverage = calculate_coverage(high_dim_vectors, threshold)
print(f"空间覆盖率（阈值 {threshold:.2f}）：{coverage:.4f}")

# 模拟检索性能
query_vector = np.random.rand(1, 50)  # 模拟一个查询向量
start_time = time.time()

# 计算查询向量到所有数据点的距离并排序
distances = cdist(query_vector, high_dim_vectors, metric='euclidean').flatten()
sorted_indices = np.argsort(distances)  # 获取排序索引
top_k = 10  # 返回最近的 10 个点
top_k_results = sorted_indices[:top_k]

end_time = time.time()

# 输出检索结果
print(f"\n检索时间：{end_time - start_time:.6f} 秒")
print(f"最近的 {top_k} 个点索引：{top_k_results}")
print(f"最近的 {top_k} 个点的距离：{distances[top_k_results]}")

# 检索性能与覆盖率关系
print("\n覆盖率对检索性能的影响:")
print(f"覆盖率较低时，检索的独特结果数量可能较少；覆盖率较高时，结果分布更均匀。")